<template>
  <div class="workaddr-setting-wrapper">
    <el-tag
      type="danger"
      v-if="workaddrData&&workaddrData.length===0"
    >暂无任何工作地点</el-tag>
    <div class="workaddr-setting-content">
      <el-tag
        v-for="workaddr in dynamicTags"
        :key="workaddr"
        closable
        @close="handleClose(workaddr)"
      >{{workaddr}}</el-tag>
      <el-input
        class="input-new-tag"
        v-if="workaddrInputVisible"
        v-model="workaddrInputValue"
        ref="refworkaddr"
        size="small"
        @keyup.enter.native="handleInputConfirm"
        @blur="handleInputConfirm"
      >
      </el-input>
      <el-button
        v-else
        size="small"
        class="button-new-tag"
        @click="showInput"
      >+ 新增办公地点</el-button>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      workaddrData: [],
      dynamicTags: [],
      workaddrInputVisible: false,
      workaddrInputValue: ''
    }
  },
  created () {
    this.getworkaddrData()
  },
  methods: {
    async handleInputConfirm () {
      const workaddrInputValue = this.workaddrInputValue
      if (workaddrInputValue) {
        const { data } = await this.$http.post('/wa/add', { name: workaddrInputValue })
        console.log(data)
        if (data.error_code === 0) {
          this.$message.success('工作地点添加成功')
          this.dynamicTags.push(workaddrInputValue)
        } else {
          this.$message.error('该工作地点已存在，添加失败！')
        }
      }
      this.workaddrInputValue = ''
      this.workaddrInputVisible = false
    },
    async handleClose (tag) {
      const { data } = await this.$http.post('/wa/del', { name: tag })
      if (data.error_code === 1) {
        this.$message.error(data.msg)
      } else {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      }
    },
    showInput () {
      this.workaddrInputVisible = true
      this.$nextTick(_ => {
        this.$refs.refworkaddr.$refs.input.focus()
      })
    },
    // 获取分类数据
    async getworkaddrData () {
      const { data } = await this.$http.get('/wa/getlist')
      this.workaddrData = data.data
      this.workaddrData.map(item => {
        this.dynamicTags.push(item.name)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/mixin";
.workaddr-setting-wrapper {
  display: flex;
  .workaddr-setting-content {
    display: flex;
    flex-flow: row wrap;
    @include tag(20px);
  }
}
</style>
